<?php

namespace App\Http\Controllers;

use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

use Illuminate\Support\Facades\DB;
use App\Tools\Func;
use App\Models\User;
use App\Models\Jiuzhenren;

class JiuzhenrenController extends Controller
{
	use Func;
	
	// 诊人列表
	public function jiuzhenren(Request $request)
	{
		$res = Jiuzhenren::where([
			'user_id' => $request->user_id ?? 1,
			'state' => 0
		])->get();

	    return $this->returnJson(0, 'success', $res);
	}
	
	// 添加就诊人
	public function jiuzhenrenAdd(Request $request)
	{
		if (!$res = Jiuzhenren::create([
			'user_id' => $request->user_id ?? 1,
			'jiuzhenren_name' => $request->jiuzhenren_name,
			'sex' => $request->sex,
			'age' => $request->age,
			'phone' => $request->phone,
			'idcard' => $request->idcard,
			'address' => $request->address,
			'qudao' => $request->qudao,
			'created_at' => date('Y-m-d H:i:s'),
		])) {
            return $this->returnJson(1, '添加失败', $res);
        }

        return $this->returnJson(0, '添加成功', $res);
	}
	
	// 就诊人设置默认
	public function jiuzhenrenDefault(Request $request)
	{
		$res = Jiuzhenren::where([
			'id' => $request->id,
			'user_id' => $request->user_id ?? 1,
		])->first();
		if ($res->is_default) {
			return $this->returnJson(1, '已经是默认设置', $res);
		}
		
		Jiuzhenren::where([
			'user_id' => $request->user_id ?? 1,
		])->update([
			'is_default' => 0
		]);
		
		if (!Jiuzhenren::where([
			'id' => $request->id,
			'user_id' => $request->user_id ?? 1,
		])->update([
			'is_default' => $request->is_default
		])) {
            return $this->returnJson(1, '设置失败', $res);
        }

        return $this->returnJson(0, 'success', $res);
	}
	
	// 删除就诊人
	public function jiuzhenrenDel(Request $request)
	{
		if (!Jiuzhenren::where([
			'id' => $request->id,
			'user_id' => $request->user_id ?? 1,
		])->update([
			'state' => 1,
			'is_default' => 0
		])) {
		    return $this->returnJson(1, '删除失败', $res);
		}
		return $this->returnJson(0, 'success');
	}
	
	// 获取默认就诊人
	public function jiuzhenrenDefaultGet(Request $request)
	{
		$res = Jiuzhenren::where([
			'user_id' => $request->user_id ?? 1,
			'is_default' => 1
		])->first();
		
		return $this->returnJson(0, 'success', $res);
		
	}

	

}
